package com.tl.common.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import org.apache.http.util.EncodingUtils;

import android.os.Environment;
import android.os.StatFs;

public class StorageUtil {

	/**
	 * 
	 * @return ROM存储路径
	 */
	public static String getInternalMemoryPath() {
		return Environment.getDataDirectory().getPath();
	}

	/**
	 * 
	 * @return 内置sd卡路径
	 */
	public static String getExternalMemoryPath() {
		// return Environment.getExternalStorageDirectory().getPath();
		return "/storage/sdcard0";
	}

	/**
	 * 
	 * @return 外置sd卡路径
	 */
	public static String getSDCard2MemoryPath() {
		return "/storage/sdcard1";
	}

	/**
	 * 
	 * @param path
	 *            文件路径
	 * @return 文件路径的StatFs对象
	 * @throws Exception
	 *             路径为空或非法异常抛出
	 */
	public static StatFs getStatFs(String path) {
		try {
			return new StatFs(path);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 
	 * @param stat
	 *            文件StatFs对象
	 * @return 剩余存储空间的MB数
	 * 
	 */
	public static float calculateSizeInMB(StatFs stat) {
		if (stat != null)
			return stat.getAvailableBlocks()
					* (stat.getBlockSize() / (1024f * 1024f));
		return 0.0f;
	}

	/**
	 * 
	 * @return ROM剩余存储空间的MB数
	 */
	public static float getAvailableInternalMemorySize() {

		String path = getInternalMemoryPath();// 获取数据目录
		StatFs stat = getStatFs(path);
		return calculateSizeInMB(stat);
	}

	/**
	 * 
	 * @return 内置SDCard剩余存储空间MB数
	 */
	public static float getAvailableExternalMemorySize() {

		String path = getExternalMemoryPath();// 获取数据目录
		StatFs stat = getStatFs(path);
		return calculateSizeInMB(stat);

	}

	/**
	 * 
	 * @return 外置SDCard剩余存储空间MB数
	 */
	public static float getAvailableSDCard2MemorySize() {

		// String status = Environment.getExternalStorageState();
		// if (status.equals(Environment.MEDIA_MOUNTED)) {
		// }
		String path = getSDCard2MemoryPath(); // 获取数据目录
		StatFs stat = getStatFs(path);
		return calculateSizeInMB(stat);

	}

	/**
	 * 遍历 "system/etc/vold.fstab” 文件，获取全部的Android的挂载点信息
	 * 
	 * @return
	 */
	private static ArrayList<String> getDevMountList() {
		String[] toSearch = readFile("/etc/vold.fstab").split(" ");
		ArrayList<String> out = new ArrayList<String>();
		for (int i = 0; i < toSearch.length; i++) {
			if (toSearch[i].contains("dev_mount")) {
				if (new File(toSearch[i + 2]).exists()) {
					out.add(toSearch[i + 2]);
				}
			}
		}
		return out;
	}

	// 读数据
	public static String readFile(String fileName) {
		File file = new File(fileName);
		String res = "";

		FileInputStream fis;
		try {
			fis = new FileInputStream(file);
			int length = fis.available();

			byte[] buffer = new byte[length];
			fis.read(buffer);

			res = EncodingUtils.getString(buffer, "UTF-8");

			fis.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return res;

	}

	/**
	 * 获取扩展SD卡存储目录
	 * 
	 * 如果有外接的SD卡，并且已挂载，则返回这个外置SD卡目录 否则：返回内置SD卡目录
	 * 
	 * @return
	 */
	public static String getExternalSdCardPath() {
		boolean sdCardExist = Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED); // 判断sd卡是否存在

		if (sdCardExist) {
			File sdCardFile = new File(Environment
					.getExternalStorageDirectory().getAbsolutePath());
			return sdCardFile.getAbsolutePath();
		}

		String path = null;

		File sdCardFile = null;

		ArrayList<String> devMountList = getDevMountList();

		for (String devMount : devMountList) {
			File file = new File(devMount);

			if (file.isDirectory() && file.canWrite()) {
				path = file.getAbsolutePath();

				String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmmss")
						.format(new Date());
				File testWritable = new File(path, "test_" + timeStamp);

				if (testWritable.mkdirs()) {
					testWritable.delete();
				} else {
					path = null;
				}
			}
		}

		if (path != null) {
			sdCardFile = new File(path);
			return sdCardFile.getAbsolutePath();
		}

		return null;
	}

}
